require "Array"
--1|A|5|2|NN382|(),();1|D|2|5|NB64;1|A|5|2|BN181|(),();1|A|8|2|ND562|(),();1|D|3|5|NN107|(),();2|AS|5|0|P|(45,46,47);2|A|5|3|PN463|(45,46,47),();2|D|3|5|NN79|(),(45,46,47);2|A|8|3|ND605|(),()

local data="1|A|5|2|NN382|(),();1|D|2|5|NB64;1|A|5|2|BN181|(),();1|A|8|2|ND562|(),();1|D|3|5|NN107|(),();2|AS|5|0|P|(45,46,47);2|A|5|3|PN463|(45,46,47),();2|D|3|5|NN79|(),(45,46,47);2|A|8|3|ND605|(),()"

local split = function (data, flag)
  if data==nil then return nil;end
  pos=0
  local arr = Array:create()
  while 1 do
    local i, j = string.find(data, flag, pos)
    if i==nil or pos>500 then break end
    local tmp = string.sub(data, pos, i-1)
    pos = j+1
    arr:append(tmp) 
  end
  arr:append(string.sub(data, pos))
  return arr
end

--print(string.sub("fda", 6, 6))

parserFightScript = function(data)
local seq = split(data, ";")
local fightSeq=Array:create()
for i=0,seq:size()-1 do
  print("#----", seq:at(i))
  local ts = split(seq:at(i), "|")
  --ts:log()
  local res = {}
  res.direction = string.sub(ts:at(1), 1, 1)
  res.attackType = string.sub(ts:at(1), 2, 2)
  res.attackPos = string.sub(ts:at(2), 1, 1) 
  res.defend = Array:create()
  local tseq1 = split(ts:at(3), ",")
  local tseq2 = split(ts:at(4), ",")
  local tseq3 = split(ts:at(5), ",")

  --print(tseq1, tseq1:size())  
  for j=0, tseq1:size()-1 do
    local a = { defendPos=string.sub(tseq1:at(j), 1, 1), 
                defendType=string.sub(tseq2:at(j), 2, 2),
                hurt=string.sub(tseq2:at(j), 3),
              }
    if tseq3~=nil then a.buf=tseq3:at(j+1) end   
    --for k,v in pairs(a) do print(k,v) end
    res.defend:append(a)
  end
  fightSeq:append(res)
  --for k,v in pairs(res) do print(k,v) end
end
return fightSeq 
end

local fightSeq=parserFightScript(data)

for i=0,fightSeq:size()-1 do
  print("----", i, "------")
  print(fightSeq:at(i).direction, fightSeq:at(i).attackType, fightSeq:at(i).attackPos)
  for j=0,fightSeq:at(i).defend:size()-1 do
    local t = fightSeq:at(i).defend:at(j)
    print("  ", t.defendPos, t.defendType, t.hurt, t.buf)
  end
end
